import { Provide, Inject } from '@midwayjs/core';
import { SMS_TYPE } from '../enums/sms-type';
import { RedisService } from '@midwayjs/redis';
import { createSMS } from '../utils/tools';

@Provide()
export class SmsService {
  @Inject()
  reidsService: RedisService;

  async checkSMS(phone, sms, type: SMS_TYPE) {
    if (type === SMS_TYPE.REGISTER) {
      const redisSms = this.reidsService.get(this.createSMSKey(phone, type));
      return sms === redisSms;
    }
  }

  async createSMS(phone: string, type = SMS_TYPE.REGISTER) {
    // 发送成功
    const sms = createSMS();
    this.reidsService.set(this.createSMSKey(phone, type), sms, 'EX', 15 * 60);
    return { success: true, sms };
  }

  createSMSKey(phone: string, type = SMS_TYPE.REGISTER) {
    return phone + '-' + type;
  }
}
